package com.swfee.qinben.base;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.Toast;

public class DoPickMultimediaBaseActivity extends AppBaseActivity {

	private static final int CAMERA_WITH_DATA = 3023;

	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	/* 用来标识请求gallery的activity */
	private static final int VEDIO_PICKED_WITH_DATA = 4020;

	/* 用来标识请求gallery的activity */
	private static final int VIDEO_CAPTURE_WITH_DATA = 4021;

	/* 拍照的照片存储位置 */
	private static final File CAMERA_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");

	private File mCurrentFile;// 照相机拍照得到的图片或視頻

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
			final Bitmap photo = data.getParcelableExtra("data");
			// 下面就是显示照片了
			System.out.println(photo);
			// 缓存用户选择的图片
			// img = getBitmapByte(photo);
			// mEditor.setPhotoBitmap(photo);
			System.out.println("set new photo");
			Toast.makeText(this, 1111, Toast.LENGTH_LONG).show();
			break;
		}
		case CAMERA_WITH_DATA: // 照相机程序返回的,再次调用图片剪辑程序去修剪图片
			doCropPhoto(mCurrentFile);
			break;

		case VEDIO_PICKED_WITH_DATA: // 照相机选择视频
		{
			Log.d("test", "onActivityResult() requestCode:" + requestCode
					+ ",resultCode:" + resultCode + ",data:" + data);
			if (null != data) {
				Uri uri = data.getData();
				if (uri == null) {
					return;
				}
				Cursor c = getContentResolver().query(uri,
						new String[] { MediaStore.MediaColumns.DATA }, null,
						null, null);
				if (c != null && c.moveToFirst()) {
					String filPath = c.getString(0);
					Log.d("test", filPath);
				}
			}
		}
			break;
		case VIDEO_CAPTURE_WITH_DATA: // 照相机选择视频
			Log.d("test", "onActivityResult() requestCode:" + requestCode
					+ ",resultCode:" + resultCode + ",data:" + data);
			if (null != data) {
				Uri uri = data.getData();
				if (uri == null) {
					return;
				} else {
					Cursor c = getContentResolver().query(uri,
							new String[] { MediaStore.MediaColumns.DATA },
							null, null, null);
					if (c != null && c.moveToFirst()) {
						String filPath = c.getString(0);
						Log.d("test", filPath);
					}
				}
			}
			break;
		}
	}

	protected void doPickDoAction() {
		Context context = this;

		// Wrap our context to inflate list items using correct theme
		final Context dialogContext = new ContextThemeWrapper(context,
				android.R.style.Theme_Light);
		String cancel = "返回";
		String[] choices = "拍照,选择照片,拍短片,选择视频".split(",");

		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle("上传多媒体");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
						case 2:

							String status = Environment
									.getExternalStorageState();
							if (!status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								// 没有sd卡
								// Toast.makeText(DoPickMultimediaBaseActivity.this,"没有SD卡",
								// Toast.LENGTH_LONG).show();
								return;
							}
							if (which == 0) {
								doTakePhoto();// 用户点击了从照相机获取
							} else {
								doVedioCapture();
							}
							break;
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;

						case 3:
							doPickVedio();
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			CAMERA_DIR.mkdirs();// 创建照片的存储目录
			mCurrentFile = new File(CAMERA_DIR, getThisFileName("jpg"));// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "未找到。。。", Toast.LENGTH_LONG).show();
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	/**
	 * 用当前时间给取得的图片命名
	 * 
	 */
	private String getThisFileName(String suffex) {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		return dateFormat.format(date) + "_qb" + "." + suffex;
	}

	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "未找到", Toast.LENGTH_LONG).show();
		}
	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Toast.makeText(this, "异常了....", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	public static Intent getVideoPickIntent() {

		Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
		intent.setType("video/*"); // 查看类型 String IMAGE_UNSPECIFIED = "image/*";
		Intent wrapperIntent = Intent.createChooser(intent, null);

		return wrapperIntent;
	}

	public static Intent getVideoCaptureIntent() {

		// 拍摄视频
		int durationLimit = 30; // SystemProperties.getInt("ro.media.enc.lprof.duration",
								// 60);
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);// 1是高清
		intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, durationLimit);
		return intent;

	}

	// 请求Gallery程序
	protected void doPickVedio() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getVideoPickIntent();
			startActivityForResult(intent, VEDIO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "未找到", Toast.LENGTH_LONG).show();
		}
	}

	// 请求Gallery程序
	protected void doVedioCapture() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getVideoCaptureIntent();
			startActivityForResult(intent, VIDEO_CAPTURE_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "未找到11", Toast.LENGTH_LONG).show();
		}
	}

}
